package org.jeecg.modules.business.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.business.dto.DoorLockDto;
import org.jeecg.modules.business.entity.BusDictItem;
import org.jeecg.modules.business.entity.BusDoorLock;
import org.jeecg.modules.business.entity.BusOrderSound;
import org.jeecg.modules.business.service.IBusDoorLockService;
import org.jeecg.modules.rooms.entity.CesRoomBuildingFloor;
import org.jeecg.modules.rooms.entity.CesRooms;
import org.jeecg.modules.rooms.service.CesRoomBuildingFloorServiceImpl;
import org.jeecg.modules.rooms.service.CesRoomsServiceImpl;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 门锁管理
 * @Author: jeecg-boot
 * @Date:   2023-03-20
 * @Version: V1.0
 */
@Api(tags="门锁管理")
@RestController
@RequestMapping("/business/busDoorLock")
@Slf4j
public class BusDoorLockController extends JeecgController<BusDoorLock, IBusDoorLockService> {
	@Autowired
	private IBusDoorLockService busDoorLockService;

	 @Resource
	 private CesRoomBuildingFloorServiceImpl buildingFloorService;

	 @Resource
	 private CesRoomsServiceImpl roomsService;

	/**
	 * 分页列表查询
	 *
	 * @param busDoorLock
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "门锁管理-分页列表查询")
	@ApiOperation(value="门锁管理-分页列表查询", notes="门锁管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusDoorLock>> queryPageList(BusDoorLock busDoorLock,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BusDoorLock> queryWrapper = QueryGenerator.initQueryWrapper(busDoorLock, req.getParameterMap());
		Page<BusDoorLock> page = new Page<BusDoorLock>(pageNo, pageSize);
		IPage<BusDoorLock> pageList = busDoorLockService.page(page, queryWrapper);
		pageList.getRecords().forEach(item->{
			CesRoomBuildingFloor buildInfo = buildingFloorService.getById(item.getBuildId());
			if (buildInfo != null) {
				item.setBuildName(buildInfo.getName());
			}
			CesRoomBuildingFloor floorInfo = buildingFloorService.getById(item.getFloorId());
			if (floorInfo != null) {
				item.setFloorName(floorInfo.getName());
			}
			CesRooms roomInfo = roomsService.getById(item.getRoomId());
			if (roomInfo != null) {
				item.setRoomNumber(roomInfo.getPrefix()+roomInfo.getName());
			}
		});
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param busDoorLock
	 * @return
	 */
	@AutoLog(value = "门锁管理-添加")
	@ApiOperation(value="门锁管理-添加", notes="门锁管理-添加")
	//@RequiresPermissions("business:bus_door_lock_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusDoorLock busDoorLock) {
		busDoorLock.setStatus(1);
		busDoorLock.setDelFlag(CommonConstant.DEL_FLAG_0);
		if(busDoorLock.getTenantId() == null || busDoorLock.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busDoorLock.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		//房间号不能重复
		LambdaQueryWrapper<BusDoorLock> queryWrapper = new LambdaQueryWrapper<BusDoorLock>();
		queryWrapper.eq(BusDoorLock::getHotelId,busDoorLock.getHotelId());
		queryWrapper.eq(BusDoorLock::getBuildId,busDoorLock.getBuildId());
		queryWrapper.eq(BusDoorLock::getFloorId,busDoorLock.getFloorId());
		queryWrapper.eq(BusDoorLock::getRoomId,busDoorLock.getRoomId());
		Long num = Long.valueOf(0);
		num = busDoorLockService.count(queryWrapper);
		if (num > 0){
			return Result.error("此房号已存在！");
		}
		busDoorLockService.save(busDoorLock);
		return Result.OK("添加成功！");
	}

	 /**
	  *   批量添加
	  *
	  * @param doorLockDto
	  * @return
	  */
	 int associationIndex;
	 @AutoLog(value = "门锁管理-批量添加")
	 @ApiOperation(value="门锁管理-批量添加", notes="门锁管理-批量添加")
	 //@RequiresPermissions("business:bus_door_lock_info:add")
	 @PostMapping(value = "/batchAdd")
	 public Result<String> batchAdd(@RequestBody DoorLockDto doorLockDto) {
		 LoginUser user = TokenUtils.getAuthUser();
		 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
		 } else {
			 throw new JeecgBootException("当前登录人租户信息错误");
		 }
		 if(!oConvertUtils.isNotEmpty(doorLockDto.radioType)) {
			 throw new JeecgBootException("规则选择错误");
		 }

//		 //获取到该酒店下已有门锁信息，删除
//		 busDoorLockService.deleteByHotelId(doorLockDto.hotelId);

		 //获取酒店所有房间信息
		 List<CesRooms> rooms = roomsService.getByHotelId(doorLockDto.hotelId);

		 List<BusDoorLock> doorLocks = new ArrayList<>();
		 if (doorLockDto.radioType.equals("4")){
			 associationIndex = Integer.parseInt(doorLockDto.front);
		 }

		 //获取到已添加的门锁信息
		 List<BusDoorLock> oldList= busDoorLockService.getByHotelId(doorLockDto.hotelId);
		 List<String> oldListIds = new ArrayList<>();
		 oldList.forEach(t->{
			 oldListIds.add(t.getRoomId());
		 });

		 rooms.forEach((item) ->{
		 	if (!oldListIds.contains(item.getId())){
				BusDoorLock doorLock = new BusDoorLock();
				doorLock.setStatus(1);
				doorLock.setDelFlag(CommonConstant.DEL_FLAG_0);
				doorLock.setTenantId(user.getRelTenantIds());
				doorLock.setHotelId(doorLockDto.hotelId);
				doorLock.setBuildId(item.getBuildId());
				doorLock.setFloorId(item.getFloorId());
				doorLock.setRoomId(item.getId());
				String association = "";
//				String roomNumber = item.getPrefix()+item.getName();
				String roomNumber = item.getName();
				switch (doorLockDto.radioType) {
					case "1":
						association = roomNumber;
						break;
					case "2":
						association = doorLockDto.front + roomNumber + doorLockDto.after;
						break;
					case "3":
						association = doorLockDto.front + roomNumber.substring(1) + doorLockDto.after;
						break;
					case "4":
						association = associationIndex + "";
						associationIndex = associationIndex + 1;
						break;
				}
				doorLock.setAssociationNumber(association);
				doorLocks.add(doorLock);
			}
		 });
		 busDoorLockService.saveBatch(doorLocks);
		 return Result.OK("添加成功！");
	 }



	/**
	 *  编辑
	 *
	 * @param busDoorLock
	 * @return
	 */
	@AutoLog(value = "门锁管理-编辑")
	@ApiOperation(value="门锁管理-编辑", notes="门锁管理-编辑")
	//@RequiresPermissions("business:bus_door_lock_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusDoorLock busDoorLock) {
		if(busDoorLock.getTenantId() == null || busDoorLock.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busDoorLock.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		//房间号不能重复
		LambdaQueryWrapper<BusDoorLock> queryWrapper = new LambdaQueryWrapper<BusDoorLock>();
		queryWrapper.eq(BusDoorLock::getHotelId,busDoorLock.getHotelId());
		queryWrapper.eq(BusDoorLock::getBuildId,busDoorLock.getBuildId());
		queryWrapper.eq(BusDoorLock::getFloorId,busDoorLock.getFloorId());
		queryWrapper.eq(BusDoorLock::getRoomId,busDoorLock.getRoomId());

		if (StringUtils.isNotBlank(busDoorLock.getId())) {
			// 编辑页面校验
			queryWrapper.ne(BusDoorLock::getId,busDoorLock.getId());
		}
		Long num = Long.valueOf(0);
		num = busDoorLockService.count(queryWrapper);
		if (num > 0){
			return Result.error("此房号已存在！");
		}
		BusDoorLock editModel = busDoorLockService.getById(busDoorLock.getId());
		editModel.setBuildId(busDoorLock.getBuildId());
		editModel.setFloorId(busDoorLock.getFloorId());
		editModel.setRoomId(busDoorLock.getRoomId());
		editModel.setAssociationNumber(busDoorLock.getAssociationNumber());
		busDoorLockService.updateById(editModel);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "门锁管理-通过id删除")
	@ApiOperation(value="门锁管理-通过id删除", notes="门锁管理-通过id删除")
	//@RequiresPermissions("business:bus_door_lock_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busDoorLockService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "门锁管理-批量删除")
	@ApiOperation(value="门锁管理-批量删除", notes="门锁管理-批量删除")
	//@RequiresPermissions("business:bus_door_lock_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busDoorLockService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "门锁管理-通过id查询")
	@ApiOperation(value="门锁管理-通过id查询", notes="门锁管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusDoorLock> queryById(@RequestParam(name="id",required=true) String id) {
		BusDoorLock busDoorLock = busDoorLockService.getById(id);
		if(busDoorLock==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busDoorLock);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busDoorLock
    */
    //@RequiresPermissions("business:bus_door_lock_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusDoorLock busDoorLock) {
        return super.exportXls(request, busDoorLock, BusDoorLock.class, "门锁管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_door_lock_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusDoorLock.class);
    }

}
